#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
from Common.stringManage import *
# from Script.writeScriptObject import *
import time
import json
import os
import sys
import shutil

# 判断是否含有妆容

def createFolders(parent):
    if not os.path.exists(parent):
        os.mkdir(parent)
        os.mkdir(parent + "/" + parent)
        os.mkdir(parent + "/" + '/thumbnails')
        os.mkdir(parent + "/" + parent + '/script')


def createScript(filename):

    file1 = open("template/template.lua", "r+")

    file = open(filename, "w")
    content = file1.read()
    pos = content.find("--config")

    if pos != -1:
        print(res)
        length = len("--config")
        print(length)
        content = replaceStr(pos, content, length, res)

    file.write(content)
    file1.close()
    file.close()

    return


def createjsonFile(filename, luafile):
    fo = open(filename, "w")
    data = {"script": luafile, "nodes": [],
            "extensions:": ["KuruFaceDetector"]}
    content = json.dumps(data)
    fo.write(content)
    fo.close()


def getResourceName(content):
    pos = content.rfind('.')
    suf = content[pos + 1:]
    if(suf == "zip"):
        return content[0:pos]
    else:
        return content


def getvalue(collection, key, defaultvalue):
    if key in collection:
        return collection[key]
    else:
        return defaultvalue


res = ""


def analysisJson(file, fileName):
    global res
    scriptPath=[]
    res = "{\n"
    with open(file, 'r') as f:
        data = json.load(f)
        res += getFilterStr(data["result"], file, fileName) + ",\n"

        items = data["result"]["items"]
        for item in items:
            if "drawType" in item:
                drawtype = item["drawType"]
                if drawtype == "BACKGROUND":
                    res += getbackgroundstr(item, fileName) + ",\n"
                elif drawtype == "FACE_SKIN_EX":
                    res += getskinExstr(item, fileName) + ",\n"
                elif drawtype == "FACE_SKIN":
                    res += getskinstr(item, fileName) + ",\n"
                elif drawtype == "COLOR_LENS":
                    res += getcolorlensstr(item) + ",\n"
                elif drawtype == "SCRIPT":
                    scriptPath.append(splitStringByIndex(item["resourceName"],".zip",0))
                else:
                    res += getstikerstr(item, fileName) + ",\n"
            else:
                res += getstikerstr(item, fileName) + ",\n"

    res += "}"
    # 输出json配置表
    # print(res)
    return res,scriptPath

# # 获取滤镜信息


def getFilterStr(item, file, fileName):
    filterFileType = splitString(
        str(getvalue(item, "filterName", "None")), ".")
    if filterFileType == "None":
        filterFileType = splitString(
            str(getvalue(item, "filterResourceName", "None")), ".")

    content = ""
    if filterFileType == "None":
        content = ("{"
                   "path=None,"
                   + "type=6,"
                   + "filterName=None,"
                   + "intensity=0.8"
                   + "}")
    elif (filterFileType == "dat")or (filterFileType == "png"):
        content = ("{"
                   "path='"+fileName+"/filter"+"/filter/" +
                   str(getvalue(item, "filterResourceName", "None"))+"',"
                   + "type=6,"
                   + "filterName='" +
                   str(getvalue(item, "filterResourceName", "None"))+"',"
                   + "intensity=0.8"
                   + "}")
    else:
        content = ("{"
                   "path="+str(getvalue(item, "filterName", "None"))+","
                   + "type=6,"
                   + "filterName=" +
                   str(getvalue(item, "filterName", "None"))+","
                   + "intensity=0.8"
                   + "}")
    return content


def getbackgroundstr(item, fileName):
    content = "{"
    rc = item["resourceName"]

    content += "path='" + fileName+"/img/img/" + getResourceName(rc) + "',"
    content += "type=0,"
    content += "scale=" + str(getvalue(item, "scale", 1)) + ","
    content += "tx=" + str(getvalue(item, "translateX", 0)) + ","
    content += "ty=" + str(getvalue(item, "translateY", 0)) + ","
    content += "anchor=KuruBackgroundImageNodeAnchorType.CENTER,stretch=KuruBackgroundImageNodeStretch.UNIFORM_FILL,"
    content += "fps=" + str(getvalue(item, "fps", 20)) + ","
    content += "blendmode=BlendMode." + \
        getvalue(item, "blendType", "None").replace("BLEND_", "").title()
    content += "}"
    return content


def getstikerstr(item, fileName):

    rc = item["resourceName"]
    content = ("{"
               + "path='" + fileName+"/img/img/"+getResourceName(rc) + "',"
               + "type=1,"
               + "scale=" + str(getvalue(item, "scale", 1)) + ","
               + "tx=" + str(getvalue(item, "translateX", 0)) + ","
               + "ty=" + str(getvalue(item, "translateY", 0)) + ","
               + "anchor=KaleStickerNodeAnchorType." +
               getvalue(item, "faceAnchorType", "CENTER") + ","
               + "location=KaleStickerNodeLocationType." +
               getvalue(item, "faceLocationType", "FACE") + ","
               + "flip=false,"
               + "fps=" + str(getvalue(item, "fps", 20)) + ","
               + "blendmode=BlendMode." +
               getvalue(item, "blendType", "Normal").replace(
                   "BLEND_", "").title()
               + "}")

    return content


def getskinExstr(item, fileName):

    rc = item["resourceName"]
    content = ("{"
               + "path='" + fileName+"/img/img/"+getResourceName(rc) + "',"
               + "type=2,"
               + "blendmode=BlendMode." +
               getvalue(item, "blendType", "Normal").replace(
                   "BLEND_", "").title()
               + "}")
    return content


def getskinstr(item, fileName):
    rc = item["resourceName"]
    content = ("{"
               + "path='" + fileName+"/img/img/"+getResourceName(rc) + "',"
               + "type=3,"
               + "scale=" + str(getvalue(item, "scale", 1)) + ","
               + "tx=" + str(getvalue(item, "translateX", 0)) + ","
               + "ty=" + str(getvalue(item, "translateY", 0)) + ","
               + "blendmode=BlendMode." +
               getvalue(item, "blendType", "Normal").replace(
                   "BLEND_", "").title()
               + "}")
    return content


def getcolorlensstr(item):
    rc = item["resourceName"]
    clrc = rc[0:rc.index(".")]
    content = ("{"
               + "path='" + clrc + "/" + clrc + ".gpb" + "',"
               + "type=4,"
               + "blendmode=BlendMode." +
               getvalue(item, "blendType", "Normal").replace(
                   "BLEND_", "").title()
               + "}")
    return content
